using Microsoft.AspNetCore.Mvc;
using System.Linq;
using XchUserInfo.BLL;
using XchUserInfo.Model;
using StudentWeb.BLL;

namespace XchUserInfo.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class XchUserController : ControllerBase
    {
        private readonly IXchUserBO _bo;
        public XchUserController(IXchUserBO bo)
        {
            _bo = bo;
        }

        // 1. 单条记录查询
        [HttpGet("{id:int}")]
        public async Task<IActionResult> Get(int id)
        {
            var data = await _bo.GetAsync(id);
            return Ok(Result.Data(data));
        }

        // 2. 添加单条记录
        [HttpPost]
        public async Task<IActionResult> Add([FromBody] XchUser req)
        {
            if (!ModelState.IsValid)
            {
                var errors = ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(e => string.IsNullOrWhiteSpace(e.ErrorMessage) ? e.Exception?.Message : e.ErrorMessage)
                    .Where(s => !string.IsNullOrWhiteSpace(s))
                    .ToArray();
                return Ok(Result.Fail("参数不合法: " + string.Join("; ", errors)));
            }
            var id = await _bo.AddAsync(req);
            return Ok(Result.OK("添加成功", new { id }));
        }

        // 3. 修改单条记录
        [HttpPut("{id:int}")]
        public async Task<IActionResult> Update(int id, [FromBody] XchUser req)
        {
            if (!ModelState.IsValid)
            {
                var errors = ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(e => string.IsNullOrWhiteSpace(e.ErrorMessage) ? e.Exception?.Message : e.ErrorMessage)
                    .Where(s => !string.IsNullOrWhiteSpace(s))
                    .ToArray();
                return Ok(Result.Fail("参数不合法: " + string.Join("; ", errors)));
            }
            var ok = await _bo.UpdateAsync(id, req);
            return Ok(Result.IsOK(ok));
        }

        // 4. 删除单条记录
        [HttpDelete("{id:int}")]
        public async Task<IActionResult> Delete(int id)
        {
            var ok = await _bo.DeleteAsync(id);
            return Ok(Result.IsOK(ok));
        }

        // 5. 分页与查询
        [HttpPost("page")]
        public async Task<IActionResult> Page([FromBody] PagedListReq req)
        {
            if (!ModelState.IsValid)
            {
                var errors = ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(e => string.IsNullOrWhiteSpace(e.ErrorMessage) ? e.Exception?.Message : e.ErrorMessage)
                    .Where(s => !string.IsNullOrWhiteSpace(s))
                    .ToArray();
                return Ok(Result.Fail("参数不合法: " + string.Join("; ", errors)));
            }
            var data = await _bo.PageAsync(req);
            return Ok(Result.Data(data));
        }
    }
}



